app.controller('vipMessagePageCtrl', function($scope, $cordovaCamera, ionicDatePicker, PopupService, $http, $myconfig, $state, $stateParams, $ionicLoading, $ionicConfig) {
    //获取本地登录储存用户信息
    $scope.userMes = JSON.parse(localStorage.getItem('user'));
    if (!$scope.userMes) {
        return;
    }
    //  console.log($scope.userMes);
    //  {"id":"8","username":"jim","mobile":"13041102857","password":"d2d02ea74de2c9fab1d802db969c18d409a8663a9697977bb1c98ccdd9de4372","modality":[],"bonusbalance":0,"integrate":0,"cumutativetime":0,"share":0,"signed":0,"createtime":"2017-03-09T03:37:01.929Z","sex":"0","birthday":"2017-03-13T16:00:00.000Z","address":"北京-东城区","headimgurl":null};
    //  JSON.parse(localStorage.getItem('user'));


    //打开选择头像
    $scope.openCam = function() {
        PopupService.CameraS($scope);
    };

    //执行拍照功能
    $scope.camPlay = function(cam) {
        document.addEventListener("deviceready", function() {

            //照片相机参数
            var options = {
                quality: 80, //保存的图像质量，范围为0 - 100
                destinationType: Camera.DestinationType.DATA_URL, //	返回值格式
                sourceType: cam, //设置图片来源
                //  Camera.PictureSourceType.CAMERA,
                MediaType: 0,
                allowEdit: true, //	选择图片前是否允许编辑
                encodingType: Camera.EncodingType.JPEG, //	JPEG = 0, PNG = 1
                targetWidth: 100, //缩放图像的宽度（像素）
                targetHeight: 100, //缩放图像的高度（像素）
                popoverOptions: CameraPopoverOptions, //	iOS,iPad弹出位置
                saveToPhotoAlbum: false, //是否保存到相册
                correctOrientation: true //设置摄像机拍摄的图像是否为正确的方向
            };

            $cordovaCamera.getPicture(options).then(function(imageData) {
                //成功后回调函数，将图片预览至手机，并保存64位地址至本地
                var image = document.getElementById('myImage');
                image.src = "data:image/jpeg;base64," + imageData;
                putb64(image.src, function() {
                        $ionicLoading.hide();

                    })
                    // Setup the loader
                    //  console.log('执行加载动作')
                $ionicLoading.show({
                    content: '图片上传中，请稍后。。。',
                    animation: 'fade-in',
                    showBackdrop: false,
                    maxWidth: 200,
                    showDelay: 0
                });
            }, function(err) {
                // error
            });

        }, false);
    };




    /*通过base64编码字符流计算文件流大小函数*/
    function fileSize(str) {
        var fileSize;
        if (str.indexOf('=') > 0) {
            var indexOf = str.indexOf('=');
            str = str.substring(0, indexOf); //把末尾的’=‘号去掉
        }

        fileSize = parseInt(str.length - (str.length / 8) * 2);
        return fileSize;
    }
    //七牛64位图片上传
    function putb64(base64, callback) {
        $http.get($myconfig.api.base_host + '/qn/token/header')
            .then(function(res) {
                // console.log(res);
                var pic = base64.split(',')[1];
                var url = 'http://up.qiniu.com/putb64/' + fileSize(pic) + '/key/' + res.data.key;
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function() {
                        if (xhr.readyState == 4) {
                            // console.log('关闭加载动作')
                            callback(JSON.parse(xhr.responseText)); //回调返回的数据
                            $scope.userMes.headimgurl = JSON.parse(xhr.response).key;
                            //修改头像
                            $http.post($myconfig.api.base_host + '/users/update_one_user', {
                                "mobile": $scope.userMes.mobile,
                                "headimgurl": $scope.userMes.headimgurl
                            }).then(function(res) {
                                if (res.data.success) {
                                    // console.log(res.data.data);
                                    localStorage.setItem('user', JSON.stringify($scope.userMes))
                                }
                            });
                            // console.log(JSON.parse(xhr.response).key);
                        }

                    }
                    // console.log(pic);
                xhr.open('POST', url, true);
                xhr.setRequestHeader('Content-Type', 'application/octet-stream');
                xhr.setRequestHeader('Authorization', 'UpToken ' + res.data.token);
                xhr.send(pic);
            });
    };


    //设置用户姓名






    $scope.useMes = {
        sex: ''
    };
    //打开选择性别
    $scope.openSex = function() {
        PopupService.popSex($scope);
        $scope.userMes.sex = $scope.useMes.sex;
    };


    //设置用户生日
    //设置插件初始设置
    var datePickerObj = {
        // 插件选择完成后回掉方法
        callback: function(val) { //Mandatory
            // console.log('Return value from the datepicker popup is : ' + val, new Date(val));
            // console.log(val);
            $scope.userMes.birthday = val;
            $http.post($myconfig.api.base_host + '/users/update_one_user', {
                "mobile": $scope.userMes.mobile,
                "birthday": new Date($scope.userMes.birthday)
            }).then(function(res) {
                if (res.data.success) {
                    localStorage.setItem('user', JSON.stringify($scope.userMes))
                }
            });
        },
        inputDate: new Date(),
        setLabel: '设置',
        todayLabel: '今天',
        closeLabel: '关闭',
        mondayFirst: false,
        weeksList: ["日", "一", "二", "三", "四", "五", "六"],
        monthsList: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一", "十二"],
        templateType: 'popup',
        from: new Date(1900, 1, 1),
        to: new Date(2020, 12, 31),
        showTodayButton: true,
        dateFormat: 'yyyy MM dd',
        closeOnSelect: false,
        disableWeekdays: [7],
    };

    //执行插件选择日期
    $scope.openDatePicker = function() {
        ionicDatePicker.openDatePicker(datePickerObj);
    };



    //设置用户手机号

    $scope.goNewPhon = function() {
        $state.go('app.vip_message_phone', { phoNo: $scope.userMes.mobile })
    };


    //修改用户登录密码
    $scope.goNewPwd = function() {
        $state.go('app.vip_message_pwdverify', { phoNo: $scope.userMes.mobile })
    };


    //修改用户所在地址
    //选择城市插件  详情参考GitHub ：https://github.com/minh8023/ionic-citypicker
    var vm = $scope.vm = {};

    //设置默认地址
    var address = $scope.userMes.address;

    vm.CityPickData = {
        areaData: [address],
        backdrop: true,
        backdropClickToClose: true,
        // defaultAreaData: [],
        tag: '-',
        cssClass: 'selectCity_vip',
        // iconClass: 'ion-location',
        //修改用户所在地址
        buttonClicked: function() {
            $http.post($myconfig.api.base_host + '/users/update_one_user', {
                "mobile": $scope.userMes.mobile,
                "address": $scope.userMes.address = vm.CityPickData.areaData.join('-')
            }).then(function(res) {
                // console.log(res.data);
                if (res.data.success) {
                    // console.log('重置');
                    // localStorage.clear();
                    localStorage.setItem('user', JSON.stringify($scope.userMes))
                        // console.log(JSON.stringify(scope.userMes));
                }
            });
        },
        // title: '请选择城市'
    };

    $scope.$on('$ionicView.enter', function() {

        $ionicConfig.views.swipeBackEnabled(false);

    });


});
